package com.zyit.service;

import com.google.gson.Gson;
import com.zyit.DataObject.T_goods;
import com.zyit.service.Impl.GoodsServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/ProductServlet")
public class ProductServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {
            List<T_goods> products = getProducts();
            // 将商品数据以JSON格式返回给前端
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            String json = new Gson().toJson(products);
            System.out.println(json);
            response.getWriter().write(json);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    private List<T_goods> getProducts() throws Exception {
        // 模拟商品数据的获取，实际中从数据库或其他数据源获取
        GoodsService goodsService = new GoodsServiceImpl();
        List<T_goods> tGoods = goodsService.SelectGoods();
//        tGoods.forEach(e -> System.out.println(e));
        // ... 添加更多商品
        return tGoods;
    }
}
